package org.boot.fast.util;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 对象转换工具类
 * 提供对象与 Map 之间的转换功能
 * @author: 最爱芫荽
 * @email: 15733440205@163.com
 */
public class ConverterUtil {

    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static Map<String, Object> convertToMap(Object obj) {
        Map<String, Object> map = new LinkedHashMap<>();
        if (obj == null) return map;
        // 只扫当前类字段，父类不管
        for (Field f : obj.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            try {
                Object v = f.get(obj);
//                if (v != null) map.put(f.getName(), v);
                map.put(f.getName(), v);
            } catch (IllegalAccessException ignored) {}
        }
        return map;
    }

    public static List<Map<String, Object>> convertToMap(List<?> list) {
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object obj : list) {
            result.add(convertToMap(obj));
        }
        return result;
    }

    public static <T> List<T> convert(List<Map<String, Object>> list, Class<T> clazz) {
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<T> result = new ArrayList<>();
        for (Map<String, Object> map : list) {
            try {
                result.add(convert(map, clazz));
            } catch (Exception e) {
                throw new RuntimeException("Jackson 转换对象失败: " + clazz.getName(), e);
            }
        }

        return result;
    }
    public static <T> T convert(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        try {
            T bean = clazz.getDeclaredConstructor().newInstance();
            for (Field f : clazz.getDeclaredFields()) {
                if (!map.containsKey(f.getName())) continue;
                f.setAccessible(true);
                try {
                    f.set(bean, map.get(f.getName()));
                } catch (IllegalAccessException ignored) {}
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException("转换失败", e);
        }
    }
}